<template>
	<div>
		<a-layout>
			<a-layout-content style="background: #fff">
				<a-page-header>
					<template slot="extra">
						<a-button @click="reload()" v-has="'outcp.query'">
							<a-icon type="reload" />
						</a-button>
						<a-button type="primary" @click="addOutcp" v-has="'outcp.create'">
							<a-icon type="file-add" />
							添加
						</a-button>
						<a-button type="primary" @click="exportTable">
							<a-icon type="export" />
							导出
						</a-button>
					</template>
					<template slot="title"> {{ $route.meta.title }} </template>
				</a-page-header>

				<a-card :bordered="false">
					<a-form-model layout="inline">
						<a-form-model-item>
							<a-input
								v-model="queryForm.searchkey"
								placeholder="物流公司名称/联系人"
							>
								<a-icon
									slot="prefix"
									type="copyright"
									style="color: rgba(0, 0, 0, 0.25)"
								/>
							</a-input>
						</a-form-model-item>

						<a-form-model-item>
							<a-button
								v-has="'outcp.query'"
								html-type="submit"
								@click="search"
								:disabled="!queryForm.searchkey"
							>
								查询
							</a-button>
						</a-form-model-item>
						<a-form-model-item>
							<a-button
								v-has="'outcp.query'"
								@click="clear"
								:disabled="!queryForm.searchkey && !queryForm.status"
							>
								<a-icon type="delete" />
								清空
							</a-button>
						</a-form-model-item>
					</a-form-model>
				</a-card>

				<div style="margin: 10px 16px 0 16px">
					<a-table
						:columns="columns"
						:data-source="data"
						@change="handleTableChange"
						:pagination="pagination"
						:loading="loading"
						:showHeader="true"
						:rowKey="
							(record, index) => {
								return index
							}
						"
					>
						<!-- <span slot="customTitle" style="color:red"><a-icon type="smile-o" />序号</span> -->

						<!-- <span slot="index" slot-scope="text">{{ "序号" }}</span> -->
						<!-- 自定义表头内容 -->
						<span slot="province" slot-scope="text, record">
							{{ getProvince(record.area_code) }}
						</span>

						<span slot="city" slot-scope="text, record">
							{{ getCity(record.area_code) }}
						</span>

						<span slot="area" slot-scope="text, record">
							{{ getArea(record.area_code) }}
						</span>

						<template v-slot:name="{ name }">
							<a-tooltip :title="name" placement="topLeft">
								{{ name }}
							</a-tooltip>
						</template>

						<template v-slot:code="{ code }">
							<a-tooltip :title="code" placement="topLeft">
								{{ code }}
							</a-tooltip>
						</template>

						<span slot="status" slot-scope="text, record">
							<template>
								<a-badge
									:status="statusTypeFilter(record.status)"
									:text="statusFilter(record.status)"
								/>
							</template>
						</span>
						<span slot="action" slot-scope="text, record">
							<template>
								<a @click="deleteOutcp(record)" v-has="'outcp.delete'">删除</a>
								<a-divider type="vertical" />
								<a @click="updateOutcp(record)" v-has="'outcp.update'">修改</a>
							</template>
						</span>
					</a-table>
				</div>
			</a-layout-content>
		</a-layout>
		<handle-table
			ref="handleTable"
			@handleOk="handleTableChange"
		></handle-table>
	</div>
</template>

<script>
	const tableObj = require("./json/table.json")
	import Outcp from "@/api/outcp"
	import momentUtil from "@/utils/day"
	import handleTable from "./components/handleForm.vue"
	import systemAreaType from "@/api/systemAreaType"
	import cache from "@/assets/js/cache"
	// import systemAreaTreeSelect from "@/components/system-area/tree-select"
	// console.log(systemAreaTreeSelect)
	export default {
		data() {
			this.statusMap = {
				1: {
					status: "success",
					text: "正常",
				},
				0: {
					status: "default",
					text: "停用",
				},
				"-1": {
					status: "error",
					text: "冻结",
				},
			}
			return {
				data_map: {},
				// systemAreaTreeSelect,
				queryForm: {
					searchkey: "",
					status: undefined, //placeholder 生效
				},
				data: [],
				columns: tableObj.columns,
				loading: false,
				pagination: {
					current: 1,
					pageSize: 20,
					total: 0,
					totalPage: 0,
					showSizeChanger: true,
					showTotal: (total) => `总 ${total} 条`,
				},
			}
		},

		filters: {
			formatStamp(stamp) {
				console.log(momentUtil.timestamp2Day(stamp, "YYYY-MM-DD hh:mm:ss"))
				return momentUtil.timestamp2Day(stamp, "YYYY-MM-DD hh:mm:ss")
			},
		},
		created() {
			this.getData()
			// 获取省市区
			this.getSystemArea()
		},

		methods: {
			getArea(area_code) {
				if (area_code && [12].includes(area_code.length)) {
					return this.data_map[area_code]
						? this.data_map[area_code]["area_name"]
						: undefined
				} else {
					return undefined
				}
			},
			getCity(area_code) {
				if (area_code && [8, 12].includes(area_code.length)) {
					return this.data_map[area_code.slice(0, 8)]
						? this.data_map[area_code.slice(0, 8)]["area_name"]
						: undefined
				} else {
					return undefined
				}
			},
			getProvince(area_code) {
				if (area_code && [4, 8, 12].includes(area_code.length)) {
					return this.data_map[area_code.slice(0, 4)]
						? this.data_map[area_code.slice(0, 4)]["area_name"]
						: undefined
				} else {
					return undefined
				}
			},
			getSystemArea() {
				systemAreaType.cache("city").then((response) => {
					console.log("省市区", response)
					if (response.code !== 1 || !response.data) {
						return
					}
					// console.log(cache.get("/cache/systemAreaType/city"))
					this.data_map = cache.get("/cache/systemAreaType/city")["data"][
						"data_map"
					]
					// this.systemAreaType = response.data.data_type
					// this.treeData = response.data.data_menu
					// this.mapData = response.data.data_map
				})
			},
			reload() {
				window.location.reload()
			},
			formatDate(timeStr) {
				console.log(timeStr)
				console.log(
					+new Date(timeStr),
					this.$formatDate("Y-M-D h:m:s", +new Date(timeStr))
				)
				return this.$formatDate("Y-M-D h:m:s", +new Date(timeStr))
			},
			deleteOutcp(record) {
				console.log(record)
				this.$modal.confirm({
					title: "提示",
					content: "是否删除？",
					okText: "确定",
					cancelText: "取消",
					centered: true,
					onOk: () => {
						console.log("删除")
						Outcp.delete(record.id).then((response) => {
							if (response.code !== 1) {
								this.$message.error(response.message)
								return
							}
							this.$message.success(response.message)
							// this.queryForm()
							this.getData()
							return
						})
					},
					onCancel: () => {
						this.$message.warning("删除取消了")
					},
				})
			},
			updateOutcp(item) {
				console.log(item)
				console.log(this.$refs.handleTable)
				this.$refs.handleTable.showModal("update", item)
			},

			handleTableChange(pagination, filters, sorter) {
				if (sorter) {
					if (sorter.order) {
						Object.assign(this.queryForm, {
							order_by: `${sorter.columnKey} ${sorter.order.slice(0, -3)}`,
						})
					} else {
						delete this.queryForm.order_by
					}
				}
				this.pagination = pagination || this.pagination
				this.getData()
			},
			getData() {
				this.loading = true
				let pageMap = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
				}
				Outcp.query(Object.assign(pageMap, this.queryForm))
					.then((res) => {
						this.loading = false
						if (res.code == 1) {
							this.pagination.total = res.page.totalSize
							this.pagination.totalPage = res.page.totalPage
							//dataSource 默认将每列数据的 key 属性作为唯一的标识
							//处理数据，否则需要excel代码里处理了
							this.data = res.data.map((item, index) => {
								return Object.assign(item, { index: index + 1 })
							})
							// ========================
							// if (this.data.length === 0) {
							// 	this.data = [
							// 		{ id: "1", name: "a" },
							// 		{ id: "2", name: "b" },
							// 	]
							// }
							// ========================
							console.log(this.data)
						}
					})
					.catch((e) => {
						this.loading = false
					})
			},
			exportTable() {
				this.$excelUtil.genTable({
					excelName: `${this.$route.meta.title}`,
					columns: tableObj.columns,
					tableData: this.handleData(this.data),
					filterKeys: ["action"],
				})
			},
			//解析数据中不能识别部分
			handleData(data) {
				return data.map((item) => {
					return Object.assign({}, item, {
						status: this.statusFilter(item.status),
					})
				})
			},
			addOutcp() {
				this.$refs.handleTable.showModal("add")
			},
			// 状态的描述
			statusFilter(status) {
				// console.log(status, this.statusMap[status + ""].text)
				return this.statusMap[status + ""]
					? this.statusMap[status + ""].text
					: undefined
			},
			// 状态的图标
			statusTypeFilter(status) {
				// console.log(status, this.statusMap[status + ""].status)
				return this.statusMap[status + ""]
					? this.statusMap[status + ""].status
					: undefined
			},
			search() {
				this.data = []
				this.pagination.current = 1
				this.getData()
			},
			clear() {
				this.queryForm.searchkey = ""
				this.queryForm.status = undefined
				this.getData()
			},
		},
		components: {
			handleTable,
			// detailPage,
		},
	}
</script>

<style lang="less" type="text/less" scoped></style>